package com.mew.user.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mew.common.dc.db.LevelConfigService;
import com.mew.common.dc.db.ProfileService;
import com.mew.common.dc.db.UserService;
import com.mew.common.dc.mapper.FriendMapper;
import com.mew.common.dc.mapper.MailMapper;
import com.mew.common.enm.GoldProcessType;
import com.mew.common.enm.MailAccessoryType;
import com.mew.common.enm.ZbmType;
import com.mew.common.entity.config.LevelVip;
import com.mew.common.entity.mail.Accessory;
import com.mew.common.entity.mail.Mail;
import com.mew.common.entity.user.Friend;
import com.mew.common.entity.user.Profile;
import com.mew.common.entity.user.User;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.user.SimpleUserResponseMessage;
import com.mew.mail.service.MailService;
import com.mew.provide.RegisterFeignService;
import com.mew.user.config.EventsLastingConfig;
import com.zebra.common.ZbmAreaType;
import com.zebra.common.ZbmMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author dylin
 * @create 2021/4/7
 */
@Service
public class FriendService {
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private MailMapper mailMapper;
    @Autowired
    private MailService mailDBService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ProfileService profileService;
    @Autowired
    private RegisterFeignService registerFeignService;
    @Autowired
    private LevelConfigService levelConfigService;
    @Autowired
    private EventsLastingConfig eventsLastingConfig;
    @Autowired
    private UserService userService;

    public SimpleUserResponseMessage getFriendApplys(long userId){
        return SimpleUserResponseMessage.builder().users(friendMapper.getFriendApplys(userId)).build();
    }
    public SimpleUserResponseMessage getFriends(long userId){
        return SimpleUserResponseMessage.builder().users(friendMapper.getFriends(userId)).build();
    }
    public SimpleUserResponseMessage getRandomUser(long userId,int limit){
        return SimpleUserResponseMessage.builder().users(friendMapper.getRandomUser(userId,limit)).build();
    }

    /**
     * 是否有好友申请
     * @param userId
     * @return
     */
    public int hasApply(long userId){
        int count =  friendMapper.selectCount(new LambdaQueryWrapper<Friend>()
            .eq(Friend::getFriendId,userId)
                .eq(Friend::getStatus,0)
        );
        return count > 0 ? 1 : 0 ;
    }

    /**
     * 是否是好友
     * @param uid
     * @param fid
     * @return
     */
    public boolean isFriend(long uid,long fid){
        List<Friend> qfs=friendMapper.selectList(new LambdaQueryWrapper<Friend>()
                .eq(Friend::getStatus,1)
                .and(wq-> {
                   wq.and(wqa->wqa.eq(Friend::getUserId,uid).eq(Friend::getFriendId,fid))
                   .or(wqa->wqa.eq(Friend::getUserId,fid).eq(Friend::getFriendId,uid));
                })
        );
        return qfs==null?false:qfs.size()>0;
    }

    /**
     * s是否重复赠送
     * @return
     */
    public boolean isGiveRep(long uid,long fid){
        return mailMapper.getLimitCount(uid,fid,GoldProcessType.Friend.code(),1)>0;
    }

    /**
     * 同意申请
     * @param userId
     * @param friendId
     */
    public void agreeApply(long userId,long friendId){
        Friend friend = Friend.builder().status(1).build();
        friendMapper.update(friend, new LambdaQueryWrapper<Friend>()
                .eq(Friend::getUserId,friendId)
                .eq(Friend::getFriendId,userId)
                .eq(Friend::getStatus,0));
        registerFeignService.zbmCommon(ZbmMessage.builder()
                .zbmType(ZbmType.AddFriend.code())
                .zbmArea(ZbmAreaType.Person.code())
                .userIds(new long[]{friendId})
                .msgJson(JSON.toJSONString(userInfoService.getSimpleInfo(userId)))
                .build());
    }

    /**
     * 拒绝申请过
     * @param userId
     * @param friendId
     */
    public void refuseApply(long userId,long friendId){
        friendMapper.delete(new LambdaQueryWrapper<Friend>()
                .eq(Friend::getUserId,friendId)
                .eq(Friend::getFriendId,userId)
                .eq(Friend::getStatus,0)
        );
    }

    /**
     * 删除申请
     * @param userId
     * @param friendId
     */
    public void deleteApply(long userId,long friendId){
        friendMapper.delete(new LambdaQueryWrapper<Friend>()
                .eq(Friend::getUserId,friendId)
                .eq(Friend::getFriendId,userId)
                .eq(Friend::getStatus,0)
        );
    }
    public int getCountFriends(long userId){
        return friendMapper.selectCount(new LambdaQueryWrapper<Friend>()
                .eq(Friend::getStatus,1)
                .and(wp->wp.eq(Friend::getUserId,userId).or().eq(Friend::getFriendId,userId))
        );
    }
    public void addFriendApply(long userId,long friendId){
        Friend friend=friendMapper.selectOne(new LambdaQueryWrapper<Friend>()
                .eq(Friend::getUserId,userId)
                .eq(Friend::getFriendId,friendId));
        if(null==friend){
            friend=Friend.builder().userId(userId).friendId(friendId).applyDate(new Date()).status(0).build();
            friendMapper.insert(friend);
        }else{
            friend.setStatus(0);
            friend.setApplyDate(new Date());
            friendMapper.updateById(friend);
        }

        registerFeignService.zbmCommon(ZbmMessage.builder()
                .zbmType(ZbmType.ApplyFriend.code())
                .zbmArea(ZbmAreaType.Person.code())
                .userIds(new long[]{friendId})
                .build());
    }
    public int deleteFriend(long userId,long friendId){
        registerFeignService.zbmCommon(ZbmMessage.builder()
                .zbmType(ZbmType.DelFriend.code())
                .zbmArea(ZbmAreaType.Person.code())
                .userIds(new long[]{friendId})
                .msgJson(String.valueOf(userId))
                .build());
        return friendMapper.delete(new LambdaQueryWrapper<Friend>()
                .and(wp->wp.eq(Friend::getUserId,userId).eq(Friend::getFriendId,friendId))
                .or(wp->wp.eq(Friend::getUserId,friendId).eq(Friend::getFriendId,userId)));
    }
    public int give(long uid,long tuid){
        if(isGiveRep(uid,tuid)){
            return ResponseCode.FriendPresented.code();
        }
        Profile profile = profileService.getRedisProfileById(uid);
        LevelVip vip = levelConfigService.getLevelVipConfig(profile.getVipLevel());
        long gold = (long) (eventsLastingConfig.getFriendGive()*(vip.getFriendGoldCoeff()+1000)/1000.0);
        User user = userService.getRedisUserById(uid);
        Mail mail=Mail.builder()
                .type(GoldProcessType.Friend.code())
                .title("ของขวัญเพื่อน")
                .content("เพื่อนของคุณ"+user.getNickname()+"ส่ง"+gold+"เหรียญทองให้คุณ โปรดเช็คทันเวลา")
                .sendUser(uid)
                .sendTime(new Date())
                .receiveUser(tuid)
                .status(0)
                .build();
        Accessory accessory=Accessory.builder()
                .type(MailAccessoryType.Gold.code())
                .quantity(gold)
                .build();
        mailDBService.insertMail(mail,accessory);
        return ResponseCode.Success.code();
    }
    public void batchGive(long uid){
        List<Long> toUids=friendMapper.getNotGiveFriends(uid);
        for (Long tuid : toUids) {
            give(uid,tuid);
        }
    }
}
